import tkinter
import random
import threading
import time
import sqlite3

# 初始化窗口
root = tkinter.Tk()
root.title("新春抽奖")
root.resizable(False, False)
root.flag = True
photo = tkinter.PhotoImage(file='final.gif')

label = tkinter.Label(root, text="",
                      font=('华文行楷', 100),
                      fg='yellow',
                      image=photo,
                      compound=tkinter.CENTER,
                     )
label.pack()


def switch():
    conn = sqlite3.connect('test.db')
    cur = conn.cursor()
    root.chosens = [rec for rec in cur.execute('SELECT NAME FROM MATES WHERE BINGO=0;')]
    rec_nums = len(root.chosens)
    while root.flag:
        i = random.randint(0, rec_nums - 1)
        label['text'] = root.chosens[i]
        time.sleep(0.01)
    chosen_one = label['text']
    if chosen_one != '':
        cur.execute('UPDATE MATES SET BINGO = 1 WHERE NAME LIKE "%s"' % chosen_one)
        conn.commit()
    print('chosen_one:', label['text'])
    print([rec for rec in cur.execute('select name from mates where bingo=1')])


# 开始按钮
def btnStartClick():
    root.flag = True
    root.t = threading.Thread(target=switch)
    root.t.start()


# 结束按钮
def btnStopClick():
    root.flag = False


# 清除抽奖结果
def btnClearClick():
    conn = sqlite3.connect('test.db')
    cur = conn.cursor()
    cur.execute('update mates set bingo=0')
    conn.commit()


menu = tkinter.Menu(root)
menu.add_command(label='开始', command=btnStartClick)
menu.add_command(label='停止', command=btnStopClick)
menu.add_command(label='清除', command=btnClearClick)
root['menu'] = menu

root.update()
print(root.winfo_width(), root.winfo_height())
print(root.winfo_screenwidth(), root.winfo_screenheight())
x_offset = (root.winfo_screenwidth() - root.winfo_width()) / 2
y_offset = (root.winfo_screenheight() - root.winfo_height()) / 2
root.geometry("+%i+%i" % (x_offset, y_offset))

# 启动主程序
root.mainloop()